from rest_framework import serializers
from api.models import UserInfo
from rest_framework.exceptions import ValidationError


class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(label="密码", min_length=8, write_only=True)
    confirm_password = serializers.CharField(label="确认密码", min_length=8, write_only=True)

    class Meta:
        model = UserInfo
        fields = ["username", "password", "phone", "confirm_password"]

    def validate_username(self, value):
        # 验证注册的用户名是否存在
        exists = UserInfo.objects.filter(username=value).exists()
        if exists:
            raise ValidationError("用户名已存在")
        return value

    def validate_phone(self, value):
        # 验证手机号是否存在
        exist = UserInfo.objects.filter(phone=value).exists()
        if exist:
            raise ValidationError("手机号已存在")
        return value

    def validate_confirm_password(self, value):
        password = self.initial_data.get('password')
        if not password == value:
            raise ValidationError("密码不一致")
        return True


class AuthSerializer(serializers.ModelSerializer):
    # 数据校验规则： 只需要传 用户名和密码 或 手机号和密码， 如都传，则数据异常
    username = serializers.CharField(label="用户名", write_only=True, required=False)
    phone = serializers.CharField(label="手机号", write_only=True, required=False)
    password = serializers.CharField(label="密码", min_length=8, write_only=True)

    class Meta:
        model = UserInfo
        fields = ["username", "phone", "password"]

    def validate_username(self, value):
        # 验证 username和phone的时候设置的可以不提交，但和业务需求不匹配，使用钩子做进一步验证
        username = self.initial_data.get('username')
        phone = self.initial_data.get('phone')
        if not username and not phone:
            raise ValidationError("用户名或手机号不能都为空")
        if username and phone:
            raise ValidationError("提交数据异常")
        return value
